package com.bytedance.danmaku.render.engine.demo.demo

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.PointF
import android.graphics.RectF
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.Nullable
import com.bytedance.danmaku.render.engine.DanmakuView
import com.bytedance.danmaku.render.engine.control.DanmakuController
import com.bytedance.danmaku.render.engine.data.DanmakuData
import com.bytedance.danmaku.render.engine.demo.R
import com.bytedance.danmaku.render.engine.demo.base.BaseDemoActivity
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.BorderDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.BorderDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.GradientDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.GradientDanmakuItemFactory
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.OfficialDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.OfficialDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.SimpleAdvancedDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.SimpleAdvancedDanmakuDrawItem
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.SimpleHasStarDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.bordertext.SimpleHasStarDanmakuDrawItem
import com.bytedance.danmaku.render.engine.demo.danmu.project.DiggEmptyTextDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.project.DiggEmptyTextDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.danmu.project.DiggEmptyTextDrawItem
import com.bytedance.danmaku.render.engine.demo.danmu.project.EmptyTextDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.project.EmptyTextDanmakuItemFactory
import com.bytedance.danmaku.render.engine.demo.danmu.project.GradientChangeDiggDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.project.GradientChangeDiggDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.danmu.project.SimpleDiggDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.project.SimpleDiggDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.danmu.widget.gradienttext.GradientTextItemFactory
import com.bytedance.danmaku.render.engine.demo.demo.advanced.AdvancedDanmakuFactory
import com.bytedance.danmaku.render.engine.demo.demo.advanced.DiggData
import com.bytedance.danmaku.render.engine.demo.utils.DIGG_STATE_OTHER_DIGG
import com.bytedance.danmaku.render.engine.demo.utils.DensityUtils.dp2px
import com.bytedance.danmaku.render.engine.demo.utils.dp
import com.bytedance.danmaku.render.engine.demo.utils.toColor
import com.bytedance.danmaku.render.engine.demo.view.RadioButtonGroupView
import com.bytedance.danmaku.render.engine.render.draw.bitmap.BitmapData
import com.bytedance.danmaku.render.engine.render.draw.text.TextData
import com.bytedance.danmaku.render.engine.touch.IItemClickListener
import com.bytedance.danmaku.render.engine.utils.CMD_PAUSE_ITEM
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_BOTTOM_CENTER
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_SCROLL
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_TOP_CENTER

/**
 * Created by dss886 on 2021/04/20.
 */
class AdvancedDanmakuActivity : BaseDemoActivity() {

    private lateinit var mController: DanmakuController
    private var mDiggBitmap: Bitmap? = null
    private var mRoundBitmap: Bitmap? = null
    private var mPausingItem: DanmakuData? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_advanced_danmaku
    }

    override fun init() {
        mController = findViewById<DanmakuView>(R.id.danmaku_view).controller
        mController.registerDrawItemFactory(AdvancedDanmakuFactory())
        mController.registerDrawItemFactory(GradientTextItemFactory())
        val borderDanmakuFactory = BorderDanmakuFactory()
        mController.registerDrawItemFactory(borderDanmakuFactory)
        mController.registerDrawItemFactory(OfficialDanmakuFactory())
        mController.registerDrawItemFactory(GradientDanmakuItemFactory())
        mController.registerDrawItemFactory(SimpleHasStarDanmakuDrawItem.SimpleHasStarDanmakuFactory())
        mController.registerDrawItemFactory(SimpleAdvancedDanmakuDrawItem.SimpleAdvancedDanmakuFactory())
        mController.registerDrawItemFactory(GradientChangeDiggDanmakuFactory())
        mController.registerDrawItemFactory(DiggEmptyTextDanmakuFactory())
        mController.registerDrawItemFactory(EmptyTextDanmakuItemFactory())
        mController.registerDrawItemFactory(SimpleDiggDanmakuFactory())
        val contents = resources.getStringArray(R.array.danmaku_text_contents)
        mDiggBitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_test)
        mRoundBitmap = BitmapFactory.decodeResource(resources, R.mipmap.test)
//        mController.setData(mDanmakuData)
        mController.start()
//        mDiggBitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_digg)
//        mRoundBitmap = BitmapFactory.decodeResource(resources, R.mipmap.test)
        mController.config.scroll.apply {
            lineMargin = dp2px(30f).toFloat()
            marginTop = dp2px(30f).toFloat()
            lineCount = 2
        }
        mController.config.scroll.moveTime=8000L
        mController.itemClickListener = object : IItemClickListener {
            override fun onDanmakuClick(data: DanmakuData, itemRect: RectF, clickPoint: PointF) {
//                mController.pause()
                Log.e("Advanced88", "onDanmakuClick: ")
                if (data is BorderDanmaku) {
//                    data.simpleAdvancedDanmaku?.diggData?.diggText?.apply {
//                        text = " "
//                    }
//                    mController.config.text.apply {
//                        size=100f
//                    }
                }else if(data is GradientChangeDiggDanmaku)
                {
                    data.mDiggEmptyTextDanmaku?.apply {
                        diggText?.text="123"
                        diggIcon?.bitmap=mRoundBitmap
                    }
                    mController.invalidateView()
                }
                Toast.makeText(
                    this@AdvancedDanmakuActivity,
                    "Click: text=${
                        isInRightMarginAreaSafe(
                            this@AdvancedDanmakuActivity,
                            itemRect,
                            clickPoint.x,
                            clickPoint.y,
                            50F
                        )
                    }",
                    Toast.LENGTH_SHORT
                ).show()

//                val datas=data as? AdvancedDanmakuData
//                datas?.apply {
//                    textData?.text="点击修改文字"
//                    diggData?.diggText?.text="1000000"
//                    diggData?.diggIcon?.bitmap=BitmapFactory.decodeResource(resources, R.mipmap.ic_digg)
//                    diggData?.diggIcon?.tintColor=R.color.white.toColor
//                }
//                findViewById<DanmakuView>(R.id.danmaku_view).apply {
//                    requestLayout()
//                    invalidate()
//                }
//                mController.invalidateView()
//                Toast.makeText(this@AdvancedDanmakuActivity, "Click: text=${(data as? TextData)?.text}", Toast.LENGTH_SHORT).show()
//                mPausingItem = if (mPausingItem == null) {
//                    mController.executeCommand(CMD_PAUSE_ITEM, data)
//                    data.drawOrder = Integer.MAX_VALUE
//                    data
//                } else {
////                    mController.executeCommand(CMD_RESUME_ITEM, mPausingItem)
////                    data.drawOrder = DRAW_ORDER_DEFAULT
//                    null
//                }
            }
        }

        findViewById<RadioButtonGroupView>(R.id.config_bounds)?.apply {
            setUp("ShowBounds", arrayOf("no", "yes"), 0) { index, _ ->
                mController.config.debug.showBounds = index > 0
            }
        }

        findViewById<RadioButtonGroupView>(R.id.config_profiler)?.apply {
            setUp("ShowProfiler", arrayOf("no", "yes"), 0) { index, _ ->
                mController.config.debug.showDrawTimeCost = index > 0
            }
        }

        findViewById<View>(R.id.add_common_danmaku).setOnClickListener {
//            mController.config.text.apply {
//                val current=size
//                size=current+10F
//            }
//            mController.addFakeData(AdvancedDanmakuData().apply {
//                textData = TextData().apply {
//                    text = contents.random()
//                    textStrokeWidth=2f
//                    textStrokeColor=Color.BLACK
//                }
//                layerType = LAYER_TYPE_SCROLL
//            })
            mController.config.text.includeFontPadding=false
            mController.addFakeData(OfficialDanmaku().apply {
                useGradient=true
                officialIcon = BitmapData().apply {
                    width = dp2px(28F).toFloat()
                    height = dp2px(28F).toFloat()
                    bitmap = mRoundBitmap
                }
                gradientChangeDiggDanmaku=GradientChangeDiggDanmaku().apply {
                    useGradient=true
                    mTextData =TextData().apply {
                        text="小简提醒你，记得记笔记哦～"
                        textStrokeWidth = dp2px(0.6f).toFloat()
                        textStrokeColor = Color.BLACK
                        textSize=sp2px(16F).toFloat()
                        textColor=Color.WHITE
                    }
                    mGradientDanmaku=GradientDanmaku().apply {
                        text="小简提醒你，记得记笔记哦～"
                        textSize=sp2px(16F).toFloat()
                        textStrokeWidth = dp2px(0.6f).toFloat()
                        textStrokeColor = Color.BLACK
                        gradientColors=intArrayOf(Color.RED,Color.YELLOW)
                    }
                    mDiggEmptyTextDanmaku= DiggEmptyTextDanmaku().apply {
                        diggText= EmptyTextDanmaku().apply {
                            text="32"
                            textStrokeWidth = dp2px(0.6f).toFloat()
                            textStrokeColor = Color.BLACK
                        }
                        diggIcon= BitmapData().apply {
                            width=dp2px(31f).toFloat()
                            height=dp2px(22f).toFloat()
                            bitmap = mDiggBitmap
                        }
                    }
                }
                layerType = LAYER_TYPE_SCROLL
            })
        }

        findViewById<View>(R.id.add_danmaku_with_digg).setOnClickListener {
            mController.addFakeData(TextData().apply {
                text = "测试渐变文字士大夫精神独立房间都是垃圾上岛咖啡就是垃圾焚烧炉打"
                textStrokeWidth = 5f
                textStrokeColor = Color.BLACK
                textSize=50f
                textColor=Color.RED
                layerType = LAYER_TYPE_SCROLL
            })
//            mController.addFakeData(GradientChangeDiggDanmaku().apply {
//                layerType = LAYER_TYPE_SCROLL
//                useGradient=true
//                mGradientDanmaku?.apply {
//                    text="测试渐变文字"
//                    textSize=40f
//                    gradientColors=intArrayOf(Color.RED,Color.YELLOW)
//                }
//                mDiggEmptyTextDanmaku?.apply {
//                    diggIcon= BitmapData().apply {
//                        width=43f
//                        height=43f
//                        bitmap = mDiggBitmap
//                    }
//                    diggText= EmptyTextDanmaku().apply {
//                        text="加一"
//                    }
//                }
//            })
//            mController.addFakeData(SimpleDiggDanmaku().apply {
//                useGradient=false
//                layerType = LAYER_TYPE_SCROLL
//                mTextData =TextData().apply {
//                    text="测试渐变文字"
//                    textStrokeWidth = 5f
//                    textStrokeColor = Color.BLACK
//                    textSize=50f
//                    textColor=Color.RED
//                }
//                mGradientDanmaku=GradientDanmaku().apply {
//                    text="测试渐变文字"
//                    textSize=50f
//                    textStrokeWidth = 5f
//                    textStrokeColor = Color.BLACK
//                    gradientColors=intArrayOf(Color.RED,Color.YELLOW)
//                }
//                mDiggEmptyTextDanmaku= DiggEmptyTextDanmaku().apply {
//                    diggText= EmptyTextDanmaku().apply {
//                        text="5"
//                        textStrokeWidth = 5f
//                        textStrokeColor = Color.BLACK
//                    }
//                    diggIcon= BitmapData().apply {
//                        width=dp2px(31f).toFloat()
//                        height=dp2px(22f).toFloat()
//                        bitmap = mDiggBitmap
//                    }
//                }
//            })
//            mController.addFakeData(BorderDanmaku().apply {
//                simpleAdvancedDanmaku = SimpleAdvancedDanmaku().apply {
//                    textData = TextData().apply {
//                        textColor=Color.YELLOW
//                        text = contents.random()
//                        textStrokeWidth=5f
//                        textStrokeColor=Color.BLACK
//                    }
//                    diggData = DiggData().apply {
//                        diggState = DIGG_STATE_OTHER_DIGG
//                        diggText = TextData().apply {
//                            text = "加一"
//                        }
//                        diggIcon = BitmapData().apply {
//                            width = 43f
//                            height = 43f
//                            bitmap = mDiggBitmap
//                            tintColor = R.color.white.toColor
//                        }
//                    }
//                }
//                layerType = LAYER_TYPE_SCROLL
//            })
//            mController.addFakeData(SimpleAdvancedDanmaku().apply {
//                diggIsRight = true
//                textData = TextData().apply {
//                    textColor=Color.YELLOW
//                    textSize=40f
//                    text = contents.random()
//                }
//                diggData=DiggData().apply {
//                    diggState=DIGG_STATE_OTHER_DIGG
//                    diggText = TextData().apply {
//                        textSize=40f
//                        text = "加一"
//                    }
//                    diggIcon = BitmapData().apply {
//                        width=43f
//                        height=43f
//                        bitmap = mDiggBitmap
//                        tintColor = R.color.white.toColor
//                    }
//                }
//                layerType = LAYER_TYPE_SCROLL
//            })
//            mController.addFakeData(AdvancedDanmakuData().apply {
//                textData = TextData().apply {
//                    text = contents.random()
//                }
//                diggData = DiggData().apply {
//                    diggState = DIGG_STATE_OTHER_DIGG
//                    diggText = TextData().apply {
//                        text = (1..30).random().toString()
//                        textColor = R.color.white.toColor
//                    }
//                    diggIcon = BitmapData().apply {
//                        width = 12.dp
//                        height = 12.dp
//                        bitmap = mDiggBitmap
//                        tintColor = R.color.white.toColor
//                    }
//                }
//                layerType = LAYER_TYPE_SCROLL
//            })
        }

        findViewById<View>(R.id.add_danmaku_with_self_digg).setOnClickListener {
            mController.addFakeData(BorderDanmaku().apply {
                layerType = LAYER_TYPE_SCROLL
                gradientChangeDiggDanmaku=GradientChangeDiggDanmaku().apply {
                    useGradient=false
                    mTextData =TextData().apply {
                        text="测试渐变文字fdjklasjflkdasjklf"
                        textStrokeWidth = 8f
                        textStrokeColor = Color.BLACK
                        textSize=sp2px(16f).toFloat()
                        textColor=Color.RED
                    }
                    mGradientDanmaku=GradientDanmaku().apply {
                        text="测试渐变文字fjalsdjfdasj"
                        textSize=sp2px(16f).toFloat()
                        textStrokeWidth = 8f
                        textStrokeColor = Color.BLACK
                        gradientColors=intArrayOf(Color.RED,Color.YELLOW)
                    }
                    mDiggEmptyTextDanmaku= DiggEmptyTextDanmaku().apply {
                        diggText= EmptyTextDanmaku().apply {
                            text=" "
                            textStrokeWidth = 8f
                            textStrokeColor = Color.BLACK
                        }
                        diggIcon= BitmapData().apply {
                            width=dp2px(30f).toFloat()
                            height=dp2px(22f).toFloat()
                            bitmap = mDiggBitmap
                        }
                    }
                }
            })
//            mController.addFakeData(TextData().apply {
//                text = "渐变色弹幕"
//                textStrokeWidth=5f
//                textStrokeColor=Color.BLACK
//                layerType = LAYER_TYPE_SCROLL
//            })
//            mController.addFakeData(GradientDanmaku().apply {
//                text = "渐变色弹幕收到附DFJALJFAJFLAKJFJALFA"
//                textStrokeWidth = 8f
//                textStrokeColor = Color.BLACK
//                gradientColors = intArrayOf(Color.YELLOW, Color.GREEN, Color.BLUE, Color.GRAY)
//                layerType = LAYER_TYPE_SCROLL
//
//            })
//            mController.addFakeData(AdvancedDanmakuData().apply {
//                textData = TextData().apply {
//                    text = contents.random()
//                }
//                diggData = DiggData().apply {
//                    diggState = DIGG_STATE_SELF_DIGG
//                    diggText = TextData().apply {
//                        text = (1..30).random().toString()
//                        textColor = R.color.red_500.toColor
//                    }
//                    diggIcon = BitmapData().apply {
//                        width = 12.dp
//                        height = 12.dp
//                        bitmap = mDiggBitmap
//                        tintColor = R.color.red_500.toColor
//                    }
//                }
//                layerType = LAYER_TYPE_SCROLL
//            })
        }
    }

    override fun onDestroy() {
        mController.stop()
        mDiggBitmap?.recycle()
        mDiggBitmap = null
        super.onDestroy()
    }

    /**
     * 更安全的区域检测，处理各种边界情况
     */
    fun isInRightMarginAreaSafe(
        context: Context,
        rect: RectF,
        x: Float,
        y: Float,
        rightMarginDp: Float
    ): Boolean {
        // 1. 检查矩形是否有效
        if (rect.isEmpty) return false

        // 2. 检查坐标是否在矩形内
        if (x !in rect.left..rect.right || y !in rect.top..rect.bottom) {
            return false
        }

        // 3. 转换dp为px，并确保不超过矩形宽度
        val rightMarginPx = dpToPx(context, rightMarginDp)
        val effectiveMargin = minOf(rightMarginPx, rect.width())

        // 4. 计算并检测右侧区域
        val rightAreaLeft = rect.right - effectiveMargin
        return x >= rightAreaLeft
    }

    fun dpToPx(context: Context, dp: Float): Float {
        return dp * context.resources.displayMetrics.density
    }

    override fun buildDanmakuData(): List<TextData> {
        val contents = resources.getStringArray(R.array.danmaku_text_contents)
        val list = mutableListOf<TextData>()
        for (i in 0..99) {
            list.add(TextData().apply {
                text = contents.random()
                val random = Math.random()
                layerType = when {
                    random < 0.2 -> LAYER_TYPE_TOP_CENTER
                    random < 0.4 -> LAYER_TYPE_BOTTOM_CENTER
                    else -> LAYER_TYPE_SCROLL
                }
                showAtTime = i * 600L + (0..300L).random()
            })
        }
        return list
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dp2px(dpValue: Float): Int {
        val scale = resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    fun px2dp(pxValue: Float): Int {
        val scale = resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }
    fun sp2px(spValue: Float): Int {
        val scaledDensity = resources.displayMetrics.scaledDensity
        return (spValue * scaledDensity + 0.5f).toInt()
    }
}